<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>用户管理</title>
    <div th:replace="common/base"></div>
    <style>
        /* 左树 */
        #organizationTreeBar {
            padding: 10px 15px;
            border: 1px solid #e6e6e6;
            background-color: #f2f2f2;
        }

        #organizationTree {
            border: 1px solid #e6e6e6;
            border-top: none;
            padding: 10px 5px;
            overflow: auto;
            height: -webkit-calc(100vh - 125px);
            height: -moz-calc(100vh - 125px);
            height: calc(100vh - 125px);
        }

        .layui-tree-entry .layui-tree-txt {
            padding: 0 5px;
            border: 1px transparent solid;
            text-decoration: none !important;
        }

        .layui-tree-entry.ew-tree-click .layui-tree-txt {
            background-color: #fff3e0;
            border: 1px #FFE6B0 solid;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layui-row layui-col-space5">
        <div class="layui-col-md3">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 10px;">
                    <!-- 树工具栏 -->
                    <div class="layui-form toolbar" id="organizationTreeBar">
                        机构选择：
                    </div>
                    <!-- 左树 -->
                    <div id="organizationTree"></div>
                </div>
            </div>
        </div>
        <div class="layui-col-md9">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 10px;">
                    <div style="margin: 0px 0px">
                        <form class="layui-form layui-form-pane" action="">
                            <div class="layui-form-item" style="margin: 0px">
                                <div class="layui-inline">
                                    <label class="layui-form-label">用户名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="keyword" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button id="btnSearch" type="submit" class="layui-btn layui-btn-primary" lay-submit
                                            lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <script type="text/html" id="toolbarUser">
                        <div class="layui-btn-container">
                            <button class="layui-btn layui-btn-sm data-add-btn" lay-event="add"><i
                                    class="layui-icon">&#xe654;</i>添加
                            </button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete">
                                <i class="layui-icon">&#xe640;</i>删除
                            </button>
                        </div>
                    </script>

                    <table id="userTable" lay-filter="userTable"></table>

                    <script type="text/html" id="currentTableBar">
                        <a class="layui-btn layui-btn-primary layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs data-count-delete" lay-event="delete">删除</a>
                        <a class="layui-btn layui-bg-green layui-btn-xs data-count-reset" lay-event="reset">重置密码</a>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 表单弹窗 -->
<script type="text/html" id="userDialog">
    <div id="userFrm" class="layui-form layuimini-form model-form" action="" lay-filter="userFrm">
        <input type="hidden" name="id"/>
        <input type="hidden" name="isDeleted" value="0">
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">账号:</label>
            <div class="layui-input-block">
                <input name="username" placeholder="请输入账号" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">用户名:</label>
            <div class="layui-input-block">
                <input name="nickName" placeholder="请输入用户名" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">性别:</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="男" title="男" checked/>
                <input type="radio" name="gender" value="女" title="女"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">手机号:</label>
            <div class="layui-input-block">
                <input name="phone" placeholder="请输入手机号" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">电子邮件:</label>
            <div class="layui-input-block">
                <input name="email" placeholder="请输入电子邮件" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">机构：</label>
            <div class="layui-input-block">
                <div id="organizationSel" class="ew-xmselect-tree"></div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色：</label>
            <div class="layui-input-block">
                <div id="roleSel"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="userSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </div>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbState">
    <input type="checkbox" lay-filter="userTbStateCk" value="{{d.id}}" lay-skin="switch"
           lay-text="正常|锁定" {{d.enabled==1?'checked':''}} style="display: none;"/>
    <p style="display: none;">{{d.enabled==1?'正常':'锁定'}}</p>
</script>
<div th:replace="common/baseJS"></div>
<script th:inline="none">
    layui.use(['form', 'table', 'tree', 'xmSelect', 'treeTable', 'ab'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            tree = layui.tree,
            xmSelect = layui.xmSelect,
            ab = layui.ab,
            selObj, treeData, roleList;  // 左树选中数据;

        /* 渲染树形 */
        function renderTree() {
            ab.ajax({
                url: '/system/organization/findList',// 请求地址
                type: "get",// 请求提交方式
                data: {},// 发送回去的数据 JSON.stringify(data)
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        data[i].title = data[i].name;
                        data[i].id = data[i].id;
                        data[i].spread = true;
                    }
                    treeData = layui.treeTable.pidToChildren(data, 'id', 'pid');
                    tree.render({
                        elem: '#organizationTree',
                        onlyIconControl: true,
                        data: treeData,
                        height: 'full-100',
                        click: function (obj) {
                            selObj = obj;
                            $('#organizationTree').find('.ew-tree-click').removeClass('ew-tree-click');
                            $(obj.elem).children('.layui-tree-entry').addClass('ew-tree-click');
                            dplTable.reload({
                                where: {organizationIds: recursiveOrgIds(obj.data).join(",")},
                                page: {curr: 1},
                                url: '/system/user/findPage'
                            });
                        }
                    });
                    $('#organizationTree').find('.layui-tree-entry:first>.layui-tree-main>.layui-tree-txt').trigger('click');
                }
            });
        }

        renderTree();

        var dplTable = table.render({
            elem: '#userTable',
            // url: '/system/user/findPage',
            data: [],
            toolbar: '#toolbarUser',
            height: 'full-100',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'id', hide: true},
                {field: 'organizationId', title: '机构id', hide: true},
                {field: 'username', title: '账号'},
                {field: 'nickName', title: '用户名'},
                {field: 'gender', title: '性别', width: 60},
                {field: 'phone', title: '手机号', width: 120},
                {field: 'email', title: '电子邮件'},
                {
                    field: 'roles', title: '角色', templet: function (d) {
                        return d.roleList.map(function (item) {
                            return '<span class="layui-badge layui-bg-orange">' + item.name + '</span>';
                        }).join('&nbsp;&nbsp;');
                    }
                },
                {field: 'enabled', title: '状态', templet: '#userTbState', width: 100},
                {title: '操作', minWidth: 190, toolbar: '#currentTableBar', align: "center"}
            ]],
            response: {
                statusName: 'status', //规定数据状态的字段名称，默认：code
                statusCode: 200, //规定成功的状态码，默认：0
                msgName: 'hint', //规定状态信息的字段名称，默认：msg
                countName: 'total', //规定数据总数的字段名称，默认：count
                dataName: 'rows' //规定数据列表的字段名称，默认：data
            },
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        /* 初始化角色列表 */
        function initRole() {
            ab.ajax({
                url: '/system/role/findSmallList',// 请求地址
                type: "get",// 请求提交方式
                data: {},// 发送回去的数据 JSON.stringify(data)
                success: function (data) {
                    roleList = data;
                }
            });
        }

        initRole();

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            table.reload('userTable', {
                page: {curr: 1},
                where: data.field
            }, 'data');

            return false;
        });
        /* 修改用户状态 */
        form.on('switch(userTbStateCk)', function (obj) {
            var loadIndex = layer.load(2);
            ab.ajax({
                url: '/system/user/updateStatus',
                data: {userId: obj.elem.value, status: obj.elem.checked ? 1 : 0},
                type: 'get',
                success: function (res) {
                    layer.close(loadIndex);
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        ab.window.msg(res.msg, res.code);
                    } else {
                        ab.window.msg(res.msg, res.code);
                        $(obj.elem).prop('checked', !obj.elem.checked);
                        form.render('checkbox');
                    }
                }
            });
        });

        //自定义验证规则
        form.verify({
            name: function (value) {
                if (value.length < 2) {
                    return '用户名称至少得2个字符啊';
                }
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(userTable)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                showEditModel();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('userTable')
                    , data = checkStatus.data;
                if (data.length == 0) {
                    ab.window.msg("请至少选择一条数据！", "error");
                    return;
                }
                var ids = [];
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                ab.util.deleteForm({
                    url: "/system/user",// 请求地址
                    type: "delete",// 请求提交方式
                    data: JSON.stringify(ids),// 发送回去的数据 JSON.stringify(data)
                    success: function (data) {
                        $("#btnSearch").click();
                    }
                });
            }
        });

        /* 表格操作列点击事件 */
        table.on('tool(userTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                showEditModel(data);
            } else if (obj.event === 'delete') {
                ab.util.deleteForm({
                    url: "/system/user",// 请求地址
                    type: "delete",// 请求提交方式
                    data: JSON.stringify([data.id]),// 发送回去的数据 JSON.stringify(data)
                    success: function (data) {
                        $("#btnSearch").click();
                    }
                });
            } else if (obj.event === 'reset') { // 重置密码
                ab.window.confirm("确定要重置“" + data.nickName + "”的登录密码吗？", function (r) {
                    if (r) {
                        var loadIndex = layer.load(2);
                        ab.ajax({
                            url: '/system/user/resetPassword',
                            data: {userId: data.id},
                            type: 'get',
                            success: function (res) {
                                layer.close(loadIndex);
                                layer.msg(res.msg, {icon: 1});
                                ab.window.msg(res.msg, res.code);
                            }
                        });
                    }
                })
            }
        });

        //监听表格复选框选择
        table.on('checkbox(userTable)', function (obj) {
            // console.log(obj)
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            ab.window.open({
                id: "addUser",
                title: (mData ? '修改' : '添加') + '用户',
                content: $("#userDialog").html(),//"/system/user/form",
                area: "500px",
                shadeClose: false,
                success: function (layero, dIndex) {
                    ab.util.formRequired();
                    // 回显表单数据
                    form.val('userFrm', mData);
                    //监听提交
                    form.on('submit(userSubmit)', function (data) {
                        data.field.organizationId = insXmSel.getValue('valueStr');
                        if (roleXmSel.getValue('valueStr') !== "") {
                            data.field.roleList = roleXmSel.getValue('valueStr').split(",").map(function (item) {
                                return {value: item}
                            })
                        }
                        ab.util.submitForm({
                            url: "/system/user",// 请求地址
                            type: !mData ? "post" : "put",// 请求提交方式
                            data: JSON.stringify(data.field),// 发送回去的数据 JSON.stringify(data)
                            success: function (data) {
                                layer.close(dIndex);
                                $("#btnSearch").click();
                            },error:function () {

                            }
                        });
                        return true;
                    });
                    // 渲染下拉树
                    var insXmSel = xmSelect.render({
                        el: '#organizationSel',
                        height: '250px',
                        data: treeData,
                        initValue: mData ? [mData.organizationId] : [selObj.data.id],
                        model: {label: {type: 'text'}},
                        layVerify: 'required',
                        layVerType: 'msg',
                        prop: {
                            name: 'title',
                            value: 'id'
                        },
                        radio: true,
                        clickClose: true,
                        tree: {
                            show: true,
                            indent: 15,
                            strict: false,
                            expandedKeys: true
                        }
                    });
                    // 渲染角色
                    var roleXmSel = xmSelect.render({
                        el: '#roleSel',
                        // height: '250px',
                        data: roleList,
                        initValue: mData ? mData.roleList.map(function (item) {
                            return item.value
                        }) : []
                    });
                    // 禁止弹窗出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }

        /* 递归获取机构节点id */
        function recursiveOrgIds(data) {
            var ids = [data.id];
            var getIds = function (list) {
                if (list != undefined && list != null) {
                    list.forEach(function (row) {
                        ids.push(row.id);
                        if (row.children) {
                            getIds(row.children)
                        }
                    });
                }
            }
            getIds(data.children);
            return ids;
        }
    });
</script>

</body>
</html>